package com.agileai.portal.controller.wcm;

import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.SimpleHandler;
import com.agileai.hotweb.domain.core.Profile;
import com.agileai.hotweb.domain.core.Resource;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.auth.SecurityGroupManage;
import com.agileai.portal.bizmoduler.wcm.InfomationFavEditManage;
import com.agileai.portal.bizmoduler.wcm.InfomationManage;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

/**
 * generated by miscdp
 */
public class ContentProviderHandler extends SimpleHandler{
	public ContentProviderHandler(){
		super();
	}
	
	public ViewRenderer prepareDisplay(DataParam param) {
		String contentId = param.get("contentId");
		if (StringUtil.isNotNullNotEmpty(contentId)){
			InfomationManage infomationManage = this.lookupService(InfomationManage.class);
			String html = infomationManage.getInfomationContent(contentId);
			if (html != null){
				if (html.startsWith("<script>") && html.endsWith("</script>")){
					html = html.substring(8,html.length()-9);
				}
				else if (html.startsWith("<pre>") && html.endsWith("</pre>")){
					html = html.substring(5,html.length()-6);
				}
				this.setAttribute("content",html);
			}
		}
		else {
			String columnId =  param.get("columnId");
			String maxCountValue = param.get("maxCount");
			String sortPolicy = param.get("sortPolicy");
			
			JSONObject jsonObject = new JSONObject();
			int count = 0;
			List<DataRow> records = null;
			InfomationManage infomationManage = this.lookupService(InfomationManage.class);
			if (!StringUtil.isNullOrEmpty(maxCountValue) && !StringUtil.isNullOrEmpty(sortPolicy)){
				int maxCount = Integer.parseInt(maxCountValue);
				List<DataRow> tempRecords = infomationManage.findContentRecords(columnId,sortPolicy,InfomationManage.InfoState.Published);
				records = this.getAuthedRecords(tempRecords);
				count = (maxCount > records.size()) ? records.size():maxCount;
			}else{
				List<DataRow> tempRecords = infomationManage.findContentRecords(columnId,sortPolicy,InfomationManage.InfoState.Published);
				records = this.getAuthedRecords(tempRecords);
				count = records.size();
			}
			try {
				if (count > 0){
					JSONArray jsonArray = new JSONArray();
					jsonObject.put("infomations", jsonArray);
					for (int i=0;i < count;i++){
						DataRow row = records.get(i);
						if (StringUtil.isNotNullNotEmpty(columnId) &&  i == 0){
							String ptTitle = row.stringValue("PT_TITLE");
							String columnName = row.stringValue("COL_NAME");
							jsonObject.put("columnId", columnId);
							jsonObject.put("columnName", columnName);
							jsonObject.put("columnTitle", ptTitle);
						}
						JSONObject tempJsonObject = new JSONObject();
						String infomationId = row.stringValue("INFO_ID");
						String infomationTitle = row.stringValue("INFO_TITLE");
						String infomationShortTitle = row.stringValue("INFO_SHORTTITLE");
						String infomationOutline = row.stringValue("INFO_OUTLINE");
						if("".equals(infomationOutline)){
							infomationOutline = "无";
						}
						String readCount = row.stringValue("INFO_READ_COUNT");
						Date publishTime = (Date)row.get("INFO_PUBLISH_TIME");
						jsonArray.put(tempJsonObject);
						tempJsonObject.put("id", infomationId);
						tempJsonObject.put("title", infomationTitle);
						tempJsonObject.put("shortTitle", infomationShortTitle);
						tempJsonObject.put("outline", infomationOutline);
						tempJsonObject.put("readCount", readCount);
						tempJsonObject.put("publishTime", DateUtil.getDateByType(DateUtil.YYMMDDHHMI_SLANTING,publishTime));
					}
				}
				this.setAttribute("content",jsonObject.toString());
			} catch (Exception e) {
				this.log.error(e.getLocalizedMessage(), e);
			}
		}
		return new LocalRenderer(getPage());
	}
	
	@PageAction
	public ViewRenderer findInfomationGrid(DataParam param) {
		String columnId =  param.get("columnId");
		String maxCountValue = param.get("maxCount");
		String sortPolicy = param.get("sortPolicy");
		
		JSONObject jsonObject = new JSONObject();
		int count = 0;
		List<DataRow> records = null;
		InfomationManage infomationManage = this.lookupService(InfomationManage.class);
		if (!StringUtil.isNullOrEmpty(maxCountValue) && !StringUtil.isNullOrEmpty(sortPolicy)){
			int maxCount = Integer.parseInt(maxCountValue);
			List<DataRow> tempRecords = infomationManage.findContentRecords8Title(columnId,sortPolicy,InfomationManage.InfoState.Published);
			records = this.getAuthedRecords(tempRecords);
			count = (maxCount > records.size()) ? records.size():maxCount;
		}else{
			List<DataRow> tempRecords = infomationManage.findContentRecords8Title(columnId,sortPolicy,InfomationManage.InfoState.Published);
			records = this.getAuthedRecords(tempRecords);
			count = records.size();
		}
		try {
			if (count > 0){
				JSONArray jsonArray = new JSONArray();
				jsonObject.put("infomations", jsonArray);
				for (int i=0;i < count;i++){
					DataRow row = records.get(i);
					if (StringUtil.isNotNullNotEmpty(columnId) &&  i == 0){
						String ptTitle = row.stringValue("PT_TITLE");
						String columnName = row.stringValue("COL_NAME");
						jsonObject.put("columnId", columnId);
						jsonObject.put("columnName", columnName);
						jsonObject.put("columnTitle", ptTitle);
					}
					JSONObject tempJsonObject = new JSONObject();
					String infomationId = row.stringValue("INFO_ID");
					String infomationTitle = row.stringValue("INFO_TITLE");
					String infomationShortTitle = row.stringValue("INFO_SHORTTITLE");
					String infomationOutline = row.stringValue("INFO_OUTLINE");
					if("".equals(infomationOutline)){
						infomationOutline = "无";
					}
					String readCount = row.stringValue("INFO_READ_COUNT");
					Date publishTime = (Date)row.get("INFO_PUBLISH_TIME");
					jsonArray.put(tempJsonObject);
					tempJsonObject.put("id", infomationId);
					tempJsonObject.put("title", infomationTitle);
					tempJsonObject.put("shortTitle", infomationShortTitle);
					tempJsonObject.put("outline", infomationOutline);
					tempJsonObject.put("readCount", readCount);
					tempJsonObject.put("publishTime", DateUtil.getDateByType(DateUtil.YYMMDDHHMI_SLANTING,publishTime));
				}
			}
			this.setAttribute("content",jsonObject.toString());
		} catch (Exception e) {
			this.log.error(e.getLocalizedMessage(), e);
		}
		return new LocalRenderer(getPage());
	}
	
	@PageAction
	public ViewRenderer findFavInfomationGrid(DataParam param) {
		User user = (User) this.getUser();
		param.put("userCode", user.getUserCode());
		String userCode = user.getUserCode();
		String columnId =  param.get("columnId");
		param.put("favType", param.get("columnId"));
		String maxCountValue = param.get("maxCount");
		String sortPolicy = param.get("sortPolicy");
		JSONObject jsonObject = new JSONObject();
		int count = 0;
		List<DataRow> records = null;
		InfomationManage infomationManage = this.lookupService(InfomationManage.class);
		if (!StringUtil.isNullOrEmpty(maxCountValue) && !StringUtil.isNullOrEmpty(sortPolicy)){
			int maxCount = Integer.parseInt(maxCountValue);
			List<DataRow> tempRecords = infomationManage.findContentRecords2Fav(columnId,sortPolicy,InfomationManage.InfoState.Published,userCode);
			records = this.getAuthedRecords(tempRecords);
			count = (maxCount > records.size()) ? records.size():maxCount;
		}else{
			List<DataRow> tempRecords = infomationManage.findContentRecords2Fav(columnId,sortPolicy,InfomationManage.InfoState.Published,userCode);
			records = this.getAuthedRecords(tempRecords);
			count = records.size();
		}
		try {
			if (count > 0){
				JSONArray jsonArray = new JSONArray();
				jsonObject.put("infomations", jsonArray);
				for (int i=0;i < count;i++){
					DataRow row = records.get(i);
					if (StringUtil.isNotNullNotEmpty(columnId) &&  i == 0){
						DataRow countResult = this.lookupService(InfomationFavEditManage.class).getInfoCountRecord(param);
						String counts = String.valueOf(countResult.get("count"));
						String topTitle = "当前类型下的收藏记录有 "+counts+" 条";
						String columnName = row.stringValue("COL_NAME");
						jsonObject.put("columnId", columnId);
						jsonObject.put("columnName", columnName);
						jsonObject.put("columnTitle", topTitle);
					}
					JSONObject tempJsonObject = new JSONObject();
					String infomationId = row.stringValue("INFO_ID");
					String infomationTitle = row.stringValue("INFO_TITLE");
					String infomationShortTitle = row.stringValue("INFO_SHORTTITLE");
					String infomationOutline = row.stringValue("INFO_OUTLINE");
					if("".equals(infomationOutline)){
						infomationOutline = "无";
					}
					String readCount = row.stringValue("INFO_READ_COUNT");
					Date publishTime = (Date)row.get("INFO_PUBLISH_TIME");
					String favId = row.stringValue("FAV_ID");
					jsonArray.put(tempJsonObject);
					tempJsonObject.put("id", infomationId);
					tempJsonObject.put("title", infomationTitle);
					tempJsonObject.put("shortTitle", infomationShortTitle);
					tempJsonObject.put("outline", infomationOutline);
					tempJsonObject.put("readCount", readCount);
					tempJsonObject.put("publishTime", DateUtil.getDateByType(DateUtil.YYMMDDHHMI_SLANTING,publishTime));
					tempJsonObject.put("favId", favId);
				}
			}else{
				JSONArray jsonArray = new JSONArray();
				jsonObject.put("infomations", jsonArray);
				String topTitle = "当前类型下的收藏记录有 0 条";
				jsonObject.put("columnId", columnId);
				jsonObject.put("columnName", columnId);
				jsonObject.put("columnTitle", topTitle);
			}
			this.setAttribute("content",jsonObject.toString());
		} catch (Exception e) {
			this.log.error(e.getLocalizedMessage(), e);
		}
		return new LocalRenderer(getPage());
	}
	
	private List<DataRow> getAuthedRecords(List<DataRow> tempRecords){
		List<DataRow> result = new ArrayList<DataRow>();
		Profile profile = this.getProfile();
		if (profile != null){
			User user = (User)profile.getUser();
			for (int i=0;i < tempRecords.size();i++){
				DataRow row = tempRecords.get(i);
				String authType = row.stringValue("INFO_AUTH_TYPE");
				if (InfomationManage.AuthType.Private.equalsIgnoreCase(authType)){
					String infomatonId = row.stringValue("INFO_ID");
					if (user.containResouce(Resource.Type.Infomation, infomatonId)
							|| "user".equals(user.getUserCode()) || "admin".equals(user.getUserCode())){
						result.add(row);
					}
				}else{
					result.add(row);
				}
			}
		}else{
			for (int i=0;i < tempRecords.size();i++){
				DataRow row = tempRecords.get(i);
				String authType = row.stringValue("INFO_AUTH_TYPE");
				if (InfomationManage.AuthType.Public.equalsIgnoreCase(authType)){
					result.add(row);
				}
			}
		}
		return result;
	}
	
	@PageAction
	public ViewRenderer increaseReadCount(DataParam param)throws IOException {
		String responseText = FAIL;
		try {
			String infomationId = request.getParameter("infomationId");
			InfomationManage infomationManage = this.lookupService(InfomationManage.class);
			infomationManage.increaseReadCount(infomationId);
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer getLastestNews(DataParam param) {
		String responseText = null;
		try {
			InfomationManage infomationManage = this.lookupService(InfomationManage.class);
			String columnCodes = param.get("columnCodes");
			String[] codeArray = columnCodes.split(",");
			JSONObject jsonObject = new JSONObject();
			JSONArray jsonArray = new JSONArray();
			
			StringBuffer strCode =  new StringBuffer("'");
			for (int i=0;i < codeArray.length;i++){
				strCode.append(codeArray[i]).append("','");
			}
			String codeSeg = strCode.substring(0, strCode.length()-2);
			List<DataRow> tempRecords = infomationManage.getLastestNewsRecords(codeSeg);
			for(int i=0;i<tempRecords.size();i++){
				JSONObject jsonObject1 = new JSONObject();
				DataRow tempRecord = tempRecords.get(i);
				jsonObject1.put("title", tempRecord.getString("infoTitle"));
				jsonObject1.put("url", "/website/01/"+tempRecord.getString("colCode")+".ptml");
				jsonObject1.put("target",  "_self");
				jsonArray.put(jsonObject1);
			}
			jsonObject.put("datas", jsonArray);
			responseText=jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer praise(DataParam param){
		String responseText = null;
		InfomationManage infomationManage = this.lookupService(InfomationManage.class);
		String infomationId = param.getString("infomationId");
		String userCode = param.getString("userCode");
		List<DataRow> results = infomationManage.findPraiseRecords(infomationId,userCode);
		if(results.size()>0){
			responseText="已点赞，请勿重复操作！";
		}else{
			infomationManage.insertPraise(param);
			responseText=SUCCESS;
		}
		return new AjaxRenderer(responseText);
	}
	
    @PageAction
    public ViewRenderer mobileIncreaseInfoReadCounts(DataParam param){
    	String responseText = FAIL;
    	try {
    		String inputString = this.getInputString();
    		JSONObject jsonObject = new JSONObject(inputString);
        	String infomationId = jsonObject.getString("id");
        	getService().increaseReadCount(infomationId);
        	responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return new AjaxRenderer(responseText);
    }
    
    @PageAction
    public ViewRenderer mobileChangePraiseCount(DataParam param){
    	String responseText = FAIL;
    	try {
    		User user = (User) this.getUser();
        	String infomationId = param.getString("infoId");
        	String userCode = user.getUserCode();
        	List<DataRow> records = getService().findPraiseRecords(infomationId, userCode);
        	if(records.size()<1){
        		DataParam queryParam = new DataParam("USER_CODE",userCode);
            	SecurityGroupManage securityGroupManage = lookupService(SecurityGroupManage.class);
    			DataRow record =  securityGroupManage.getContentRecord("SecurityUser", queryParam);
    			String userId = record.getString("USER_ID");
            	param.put("infomationId",infomationId,"userId",userId);
            	getService().insertPraise(param);
            	responseText = SUCCESS;
        	}else{
        		getService().cancelPraiseRecord(infomationId, userCode);
        		responseText = SUCCESS;
        	}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return new AjaxRenderer(responseText);
    }	
	
    @PageAction
    public ViewRenderer mobileAddNewReview(DataParam param){
    	String responseText = FAIL;
    	try {
    		String infomationId = param.getString("ID");
    		User user = (User) this.getUser();
    		String inputString = this.getInputString();
    		JSONObject jsonObject = new JSONObject(inputString);
        	String rewContent = jsonObject.getString("rewContent");
        	String userCode = user.getUserCode();
        	InetAddress netAddress = InetAddress.getLocalHost();
        	String rewId = KeyGenerator.instance().genKey();
        	DataParam insertParam = new DataParam("REW_ID",rewId,"REW_CONTENT",rewContent,"REW_TIME",new Date(),
        			"USER_CODE",userCode,"REW_ANONYMITY","0","REW_IPADDRESS",netAddress.getHostAddress(),"INFO_ID",infomationId);
        	getService().addNewReview(insertParam);
        	responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return new AjaxRenderer(responseText);
    }	
    
	@PageAction
	public ViewRenderer getRightNews(DataParam param){
		String responseText = null;
		try{
			InfomationManage infomationManage = this.lookupService(InfomationManage.class);
			String colCode = param.getString("colCode");
			List<DataRow> results = infomationManage.getRightNews(colCode,0,20);
			JSONArray jsonArray = new JSONArray();
			for(int i=0;i<results.size();i++){
				if(i>6){
					break;
				}
				DataRow row = results.get(i);
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("title", row.stringValue("INFO_TITLE"));
				jsonObject.put("id", row.stringValue("INFO_ID"));
				jsonArray.put(jsonObject);
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("datas", jsonArray);
			responseText = jsonObject.toString();
		}catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
    protected InfomationManage getService() {
        return (InfomationManage) this.lookupService(InfomationManage.class);
    }	
}
